package com.example.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bean.BookSort;
import com.example.bean.Books;
import com.example.bean.Borrow;
import com.example.bean.Role;
import com.example.config.AuthAccess;
import com.example.service.BookSortService;
import com.example.service.BooksService;
import com.example.service.BorrowService;
import com.example.service.RoleService;
import com.example.until.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @title: RoleController
 * @Author wjf
 * @Date: 2022/9/26 17:04
 * @Version 1.0
 */
@RestController
@CrossOrigin
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BooksService booksService;

    @Autowired
    private BookSortService bookSortService;

    @Autowired
    private BorrowService borrowService;

    private String bookUploadPath ="D:/代码/项目/bookimgs/";

    @AuthAccess
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  //原文件名
        String type = FileUtil.extName(originalFilename);  //文件类型

        //定义一张图片的唯一标识吗
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type;
        File uploadFile = new File(bookUploadPath + fileUUID);

        //判断配置的文件目录是否存在，若不存在则创建一个新的目录
        File parentFile = uploadFile.getParentFile();
        if (!parentFile.exists()){
            parentFile.mkdirs();
        }

        //上传图片到磁盘
        file.transferTo(uploadFile);

        String url = "http://localhost:9090/book/img/" + fileUUID;

        return url;
    }

    @AuthAccess
    @GetMapping("/img/{fileUUID}")
    public void downLoad(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        //根据文件的唯一标识获取文件
        File uploadFile = new File(bookUploadPath + fileUUID);
        //设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        //读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

    @GetMapping("/page")
    public Result getPage(
            @RequestParam Integer current,
            @RequestParam Integer pageSize,
            @RequestParam String name,
            @RequestParam String author){
        IPage<Books> page = new Page<>(current,pageSize);
        IPage<Books> page1 = booksService.findPage(page,name,author);
        return Result.ok(page1);
    }

    @GetMapping("/{id}")
    public Result getUserById(@PathVariable("id") Integer id){
        Books book = booksService.getById(id);
        return Result.ok(book);
    }

    @GetMapping()
    public Result getSort(){
        List<BookSort> list = bookSortService.list();
        return Result.ok(list);
    }

    @PostMapping("/save")
    public Result<Boolean> saveUser(@RequestBody Books book){
        System.out.println(book);
      boolean save = booksService.save(book);
        if (save){
            return Result.ok();
        }
         return Result.fail();
    }

    @PutMapping("/update")
    public Result<Boolean> putUser(@RequestBody Books book) {
        boolean b = booksService.updateById(book);
        return Result.ok(b);
    }

    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteUser(@PathVariable Integer id) {
        boolean b = booksService.removeById(id);
        return Result.ok(b);
    }

    @DeleteMapping("/delete/batch/{ids}")
    public Result<Boolean> deleteMoreUser(@PathVariable List<Integer> ids){
        boolean b = booksService.removeByIds(ids);
        return Result.ok(b);
    }

    @PostMapping("/borrow/{bookId}/{userId}")
    public Result borrow(@PathVariable Integer bookId,@PathVariable Integer userId){
        System.out.println(userId);
        Boolean b =  booksService.findAndSaveBook(bookId,userId);
       if (b){
          return Result.ok("申请成功");
      }
          return Result.fail();
    }

    @AuthAccess
    @GetMapping("/books")
    public Result getAll(){
        List<Books> list = booksService.list();
        return Result.ok(list);
    }


}
